package com.ms.oschina.base;

import java.util.List;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;

import com.ms.oschina.bean.Constants;
import com.ms.oschina.util.HandlerUtils;
import com.ms.oschina.util.UiUtils;
import com.ms.oschina.viewholder.LoadMoreViewHolder;
import com.squareup.picasso.Picasso;

/**
 * @param <E>
 *            list数据的泛型
 * @author Administrator
 */
public abstract class SuperBaseAdapter<E> extends BaseAdapter implements
		AbsListView.OnScrollListener, AdapterView.OnItemClickListener {
	private AbsListView listView;
	private List<E> moreData = null;
	private boolean loadMore;
	private List<E> listData;

	private static final int NORMALVIEWTYPE = 1;
	private static final int LOADMOREVIEWTYPE = 0;
	private LoadMoreViewHolder mLoadMoreViewHolder;

	private boolean isLoadFailure = false;

	// 加载更多四种状态
	public static final int LOADMORE_STATUS_LOADING = 0;
	public static final int LOADMORE_STATUS_ERROR = 1;
	public static final int LOADMORE_STATUS_SUCCESS = 2;
	/**
	 * 加载全部
	 */
	public static final int LOADMORE_STATUS_FINISH = 3;

	public SuperBaseAdapter(AbsListView listView, List<E> listData) {
		this(listView, listData, false);
	}

	/**
	 * @param listData
	 * @param loadMore
	 *            是否加载跟多
	 */
	public SuperBaseAdapter(AbsListView listView, List<E> listData,
			boolean loadMore) {
		this.listData = listData;
		this.listView = listView;
		this.loadMore = loadMore;
		listView.setOnScrollListener(this);
		listView.setOnItemClickListener(this);
	}

	public List<E> getListData() {
		return listData;
	}

	public void setListData(List<E> listData) {
		if (listData == null) {
			return;
		}
		this.listData = listData;
		this.notifyDataSetChanged();// 通知数据改变
	}

	public void addListData(List<E> listData) {
		if (this.listData == null || listData == null) {
			return;
		}

		if (this.listData.containsAll(listData)) {// 已经包含无需重复添加
			return;
		}

		this.listData.addAll(listData);
		this.notifyDataSetChanged();// 通知数据改变
	}

	@Override
	public int getCount() {
		if (listData != null) {
			if (loadMore) {
				return listData.size() + 1;
			}
			return listData.size();
		}
		return 0;
	}

	@Override
	public E getItem(int position) {
		if (listData != null) {
			E e = listData.get(position);
			return e;
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@SuppressWarnings("unchecked")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		int viewType = getItemViewType(position);
		BaseViewHolder<E> holder = null;
		if (convertView == null) {
			if (viewType == LOADMOREVIEWTYPE) {// 加载更多的view
				holder = getLoadMoreViewHolder();
			} else {
				holder = getViewHolder(position, listData.get(position));
			}
		} else {
			holder = (BaseViewHolder<E>) convertView.getTag();
		}

		if (viewType == LOADMOREVIEWTYPE) {// 开始加载更多
			holder.setData(0, null);// 滑动到底部自定加载更多 ，而不是到达底部时加载跟多
		} else {
			getHolder(holder);
			holder.setData(position, listData.get(position));
		}

		return holder.getRootView();
	}

	/**
	 * 每次getView后 ，当前的ViewHolder
	 * 
	 * @param holder
	 */
	public void getHolder(BaseViewHolder<E> holder) {

	}

	private BaseViewHolder<E> getLoadMoreViewHolder() {
		if (mLoadMoreViewHolder == null) {
			mLoadMoreViewHolder = new LoadMoreViewHolder() {
				@Override
				protected int loadMore() {
					try {
						moreData = SuperBaseAdapter.this.loadMore();

						if (moreData == null) {// 子类没有覆盖方法
							// nothing
							return LOADMORE_STATUS_SUCCESS;
						} else if (moreData.size() == 0
								|| (moreData.size() < Constants.PAGESIZE && getCurrentPage() == 0)
								|| listData.containsAll(moreData)) { // 没有跟多更多数据
							// 记得恢复pageIndex；
							return LOADMORE_STATUS_FINISH;
						}

						listData.addAll(moreData);
						HandlerUtils.postTaskSafely(new Runnable() {
							@Override
							public void run() {
								// 加载数据成功
								SuperBaseAdapter.this.notifyDataSetChanged();
							}
						});

						isLoadFailure = false;
						return LOADMORE_STATUS_SUCCESS;
					} catch (Exception e) {
						// 通知加载失败
						if (!isLoadFailure) {
							loadMoreFailure();
						}
						isLoadFailure = true;
						e.printStackTrace();
					}
					return LOADMORE_STATUS_ERROR;
				}
			};
		}
		return mLoadMoreViewHolder;
	}

	protected int getCurrentPage() {
		return 0;
	}

	/**
	 * 加载更多失败时的回调
	 */
	public void loadMoreFailure() {

	}

	/*
	 * 同步
	 */
	public List<E> loadMore() throws Exception {
		return null;
	}

	@Override
	public int getViewTypeCount() {
		return super.getViewTypeCount() + 1;
	}

	@Override
	public int getItemViewType(int position) {
		if (position == listData.size()) {
			return LOADMOREVIEWTYPE;// 0
		}
		return NORMALVIEWTYPE;// 1
	}

	public abstract BaseViewHolder<E> getViewHolder(int position, E e);

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		final Picasso picasso = Picasso.with(UiUtils.getContext());
		if (scrollState == SCROLL_STATE_IDLE
				|| scrollState == SCROLL_STATE_TOUCH_SCROLL) {
			// loadMoreData(null);
			picasso.resumeTag(UiUtils.getContext());
		} else {
			picasso.pauseTag(UiUtils.getContext());
		}
	}

	/**
	 * @param str
	 *            界面 显示完成时的文字 可以为null
	 */
	public void loadMoreData(String str) {
		int lastVisiblePosition = listView.getLastVisiblePosition();
		if (lastVisiblePosition == (listView.getCount() - 1)) {
			if (mLoadMoreViewHolder != null) {
				// 加载更多
				if (mLoadMoreViewHolder != null) {
					mLoadMoreViewHolder.setData(0, null);
				}
				listView.setSelection(listView.getCount());
			}
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	/* =============== 处理item的点击事件 =============== */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		if (getItemViewType(position) == LOADMOREVIEWTYPE) {
			// 重新加载更多
		} else {
			onNormalItemClick(parent, view, position, id);
		}
	}

	/**
	 * @des 点击普通条目对应的事件处理
	 * @call 如果子类需要处理item的点击事件, 就直接覆写此方法
	 */
	public void onNormalItemClick(AdapterView<?> parent, View view,
			int position, long id) {

	}

}
